package com.wswy.wzcx.module

import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import android.os.SystemClock
import com.blankj.utilcode.util.SPUtils
import com.che.libcommon.utils.RxBus
import com.tencent.bugly.beta.Beta
import com.tencent.bugly.beta.UpgradeInfo
import com.tencent.bugly.beta.upgrade.UpgradeStateListener
import com.wswy.wzcx.BuildConfig
import com.wswy.wzcx.api.Api
import com.wswy.wzcx.model.*
import com.wswy.wzcx.module.base.Resource
import com.wswy.wzcx.module.base.SingleLiveData
import com.wswy.wzcx.module.base.onResult
import com.wswy.wzcx.module.base.onSuccess
import com.wswy.wzcx.ui.other.UpdateTools
import com.wswy.wzcx.utils.RxUtils
import io.reactivex.observers.ResourceObserver
import timber.log.Timber
import java.util.concurrent.TimeUnit

object MessageCenter {

    private const val KEY_CHECK_UPDATE = "last_check_update"
    private const val KEY_LAST_SHOW_UPDATE = "last_show_update"

    data class UnreadCount(var msg:Int=0,var feedback:Int = 0)

    data class UpgradeInfoMsg(var checking:Boolean,
                              var hasNewVersion:Boolean,
                              var manual:Boolean = false,
                              var upgradeInfo: UpgradeInfo?=null)

    //未读消息
    private val msgUnreadCountLiveData = MutableLiveData<Resource<Int?>>()
    //未读反馈
    private val feedbackUnreadCountLiveData = MutableLiveData<Resource<Int?>>()

    //最近消息，通过未读数量计算所有未读数
    private val msgNewestLiveData = MutableLiveData<MessageMode?>()

    //所有未读 包括反馈
    private val unreadCountLiveData = MutableLiveData<UnreadCount>().apply {
        value = UnreadCount()

    }

    private val upgradeInfoLiveData = MutableLiveData<UpgradeInfoMsg>().apply {
        value = UpgradeInfoMsg(false,false)
    }

    private var lastMsgReq =0L

    private val mainUpgradeLiveData = SingleLiveData<UpgradeModel>()
    private var lastFeedbackReq = 0L


    fun startObserver(){
        val userLoginObserver = object : ResourceObserver<UserMode>() {
            override fun onNext(userMode: UserMode) {

                loadUnread(true)
            }

            override fun onError(e: Throwable) {

            }

            override fun onComplete() {

            }
        }

        val userLogoutObserver = object : ResourceObserver<UserMode>() {
            override fun onNext(userMode: UserMode) {
                loadUnread(true)
            }

            override fun onError(e: Throwable) {

            }

            override fun onComplete() {

            }
        }




        val observer = object : ResourceObserver<String>() {
            override fun onNext(s: String) {
                loadMsgUnreadCount(true)
            }

            override fun onError(e: Throwable) {

            }

            override fun onComplete() {

            }
        }

//        val observerFeedback = object : ResourceObserver<String>() {
//            override fun onNext(s: String) {
//                loadFeedbackCount(true)
//            }
//
//            override fun onError(e: Throwable) {
//
//            }
//
//            override fun onComplete() {
//
//            }
//        }

        RxBus.getDefault().toObservableWithCode(InternalMsgCode.CODE_LOGIN_SUCCESS, UserMode::class.java)
                .subscribe(userLoginObserver)

        RxBus.getDefault().toObservableWithCode(InternalMsgCode.CODE_LOGOUT, UserMode::class.java)
                .subscribe(userLogoutObserver)



        RxBus.getDefault().toObservableWithCode(InternalMsgCode.CODE_MESSAGE_COUNT_CHANGE, String::class.java)
                .subscribe(observer)

//        RxBus.getDefault().toObservableWithCode(InternalMsgCode.CODE_FEEDBACK_UNREAD_COUNT_CHANGE, String::class.java)
//                .subscribe(observerFeedback)


        loadUnread(true)
    }


    fun loadUnread(force:Boolean=false) {
        loadMsgUnreadCount(force)
        //loadFeedbackCount(force)
    }

    fun loadMsgUnreadCount(force:Boolean=false){
        if (DataCenter.get().hasLogin()){
            if (force || (lastMsgReq == 0L || SystemClock.elapsedRealtime() - lastMsgReq >= TimeUnit.SECONDS.toMillis(20))){
                lastMsgReq = SystemClock.elapsedRealtime()
                Api.get().fetchPushMessage().onResult({
                    //最新消息
                    msgNewestLiveData.postValue(it)

                    val msgCount = it?.messageCount?:0

                    //发送消息  推送的，不包含反馈
                    unreadCountLiveData.value?.msg = msgCount
                    unreadCountLiveData.reSend()

                    //发送消息  所有的
                    msgUnreadCountLiveData.postValue(Resource.success(msgCount))


                },{

                })

            }


        }else{
            unreadCountLiveData.value?.msg = 0
            unreadCountLiveData.value?.feedback = 0
            unreadCountLiveData.reSend()
            msgNewestLiveData.postValue(null)
            msgUnreadCountLiveData.postValue(Resource.success(0))
        }
    }


//    private fun loadFeedbackCount(force:Boolean=false){
//        if (DataCenter.get().hasLogin()){
//            if (force || (lastFeedbackReq == 0L || SystemClock.elapsedRealtime() - lastFeedbackReq >= 1000*60)){
//
//                lastFeedbackReq = SystemClock.elapsedRealtime()
//
//                Api.get().fetchFeedbackCount().onResult({
//
//                    unreadCountLiveData.value?.feedback = it?:0
//                    unreadCountLiveData.reSend()
//
//
//                    feedbackUnreadCountLiveData.postValue(Resource.success(it))
//
//                },{
//
//
//                })
//            }
//
//        }else{
//
//            unreadCountLiveData.value?.msg = 0
//            unreadCountLiveData.value?.feedback = 0
//            unreadCountLiveData.reSend()
//
//            msgNewestLiveData.postValue(null)
//
//            feedbackUnreadCountLiveData.postValue(Resource.success(0))
//        }
//    }



    fun mainCheckUpgrade(firstCheck:Boolean=false){
        val lastCheckTime =  SPUtils.getInstance().getLong(KEY_CHECK_UPDATE,0)

        val maxCheckTime = if (BuildConfig.DEBUG) TimeUnit.SECONDS.toMillis(30) else TimeUnit.HOURS.toMillis(1)

        //每小时检测一次 测试每分钟
        if (!firstCheck && System.currentTimeMillis() - lastCheckTime < maxCheckTime){
            return
        }

        SPUtils.getInstance().put(KEY_CHECK_UPDATE,System.currentTimeMillis())

        val lastShowTime =  SPUtils.getInstance().getLong(KEY_LAST_SHOW_UPDATE,0)

        val maxShowTime = if (BuildConfig.DEBUG) TimeUnit.SECONDS.toMillis(30) else TimeUnit.DAYS.toMillis(1)

        Api.get().checkUpgrade()
                .filter { UpdateTools.hasNewVersion(it.orNull()) }
                .map {
                    it.orNull()?.let {
                        it.showMarketDialog = UpdateTools.canShowUpgradeDialog(it)
                    }
                    it
                }
                .toSingle()
                .compose(RxUtils.io2main())
                ?.onSuccess {
            if (it != null && !it.versionName.isNullOrEmpty()){
                if (it.force  == true){
                    //强制更新 忽略检测
                    SPUtils.getInstance().remove(KEY_LAST_SHOW_UPDATE)
                    mainUpgradeLiveData.postValue(it)
                }else{
                    if (System.currentTimeMillis() - lastShowTime > maxShowTime ){
                        //可显示
                        SPUtils.getInstance().put(KEY_LAST_SHOW_UPDATE,System.currentTimeMillis())
                        mainUpgradeLiveData.postValue(it)
                    }
                }
            }
        }
    }


    fun hookUpdateListener(){
        Beta.upgradeStateListener = object : UpgradeStateListener{
            override fun onUpgrading(isManual: Boolean) {
                upgradeInfoLiveData.value?.run {
                    checking = true
                    hasNewVersion = false
                    manual = isManual
                    upgradeInfo = null
                }
                upgradeInfoLiveData.reSend()
            }

            override fun onUpgradeSuccess(isManual: Boolean) {
                upgradeInfoLiveData.value?.run {
                    checking = false
                    hasNewVersion = true
                    manual = isManual
                    upgradeInfo = Beta.getUpgradeInfo()
                }

                upgradeInfoLiveData.reSend()
            }

            override fun onDownloadCompleted(isManual: Boolean) {

                normalMsg(isManual)
            }

            override fun onUpgradeNoVersion(isManual: Boolean) {
                normalMsg(isManual)
            }

            override fun onUpgradeFailed(isManual: Boolean) {
                normalMsg(isManual)
            }


            private fun normalMsg(isManual: Boolean){
                upgradeInfoLiveData.value?.run {
                    checking = false
                    hasNewVersion = false
                    manual = isManual
                    upgradeInfo = null
                }
                upgradeInfoLiveData.reSend()
            }

        }
    }

    //消息未读
    fun getMsgUnreadCountLiveData(): LiveData<Resource<Int?>> = msgUnreadCountLiveData

    //反馈未读
    fun getFeedbackCountLiveData(): LiveData<Resource<Int?>> = feedbackUnreadCountLiveData

    //所有未读数量
    fun getAllUnreadLiveData(): LiveData<UnreadCount> = unreadCountLiveData

    //更新信息
    fun getUpgradeInfoLiveData():LiveData<UpgradeInfoMsg> = upgradeInfoLiveData

    //最近消息
    fun getNewestLiveData(): LiveData<MessageMode?> = msgNewestLiveData


    fun getMainUpgradeLiveData():LiveData<UpgradeModel> = mainUpgradeLiveData
}